#include "TabManager.h"
#include "DockingArea.h"
#include "DockTab.h"
#include "DockingTabStack.h"
#include <QSettings>
#include <QDebug>
#include <cassert>

TabManager::TabManager(QObject* parent)
    : QObject(parent)
    , m_primaryArea(nullptr)
{
}

TabManager::~TabManager() {
    // 清理单例标签页缓存
    m_singletonTabs.clear();
}

// === 停靠区域管理 ===

void TabManager::setPrimaryArea(DockingArea* area) {
    // 断言：主区域不应该为空
    assert(area != nullptr && "Primary area cannot be null");
    
    m_primaryArea = area;
}

// === 标签页类型注册 ===

void TabManager::registerTabSpawner(const TabSpawnInfo& info) {
    // 断言：标签ID不应该为空
    assert(!info.tabId.isEmpty() && "Tab ID cannot be empty");
    // 断言：内容工厂不应该为空
    assert(info.contentFactory != nullptr && "Content factory cannot be null");
    
    if (info.tabId.isEmpty() || !info.contentFactory) {
        qWarning() << "TabManager::registerTabSpawner: Invalid tab info";
        return;
    }
    
    m_tabSpawners[info.tabId] = info;
    qDebug() << "Registered tab type:" << info.tabId;
}

void TabManager::unregisterTabSpawner(const QString& tabId)
{
    if (m_tabSpawners.remove(tabId) > 0)
    {
        // 如果有单例标签页，也要清理
        if (m_singletonTabs.contains(tabId))
        {
            m_singletonTabs.remove(tabId);
        }
        qDebug() << "Unregistered tab type:" << tabId;
    }
}

bool TabManager::isTabTypeRegistered(const QString& tabId) const
{
    return m_tabSpawners.contains(tabId);
}

// === 标签页生成 ===

DockTab* TabManager::spawnTab(const QString& tabId, bool forceNew)
{
    return spawnTabInArea(tabId, m_primaryArea, forceNew);
}

DockTab* TabManager::spawnTabInArea(const QString& tabId, DockingArea* area, bool forceNew)
{
    if (!area)
    {
        qWarning() << "TabManager::spawnTabInArea: No area specified";
        return nullptr;
    }
    
    if (!m_tabSpawners.contains(tabId)) {
        qWarning() << "TabManager::spawnTabInArea: Unknown tab type:" << tabId;
        return nullptr;
    }
    
    const TabSpawnInfo& info = m_tabSpawners[tabId];
    
    // 检查单例限制
    if (info.isSingleton && !forceNew) {
        if (m_singletonTabs.contains(tabId)) {
            DockTab* existingTab = m_singletonTabs[tabId];
            if (existingTab) {
                // 激活已存在的标签页
                activateExistingTab(existingTab);
                return existingTab;
            } else {
                // 清理无效引用
                m_singletonTabs.remove(tabId);
            }
        }
    }
    
    // 创建新标签页
    DockTab* newTab = createTabFromInfo(info, area);
    if (!newTab) {
        qWarning() << "Failed to create tab:" << tabId;
        return nullptr;
    }
    
    // 缓存单例标签页
    if (info.isSingleton) {
        m_singletonTabs[tabId] = newTab;
    }
    
    emit tabSpawned(newTab, tabId);
    return newTab;
}

// === 标签页查找 ===

DockTab* TabManager::findExistingTab(const QString& tabId) const {
    if (!m_primaryArea) return nullptr;
    
    // 首先检查单例缓存
    if (m_singletonTabs.contains(tabId)) {
        return m_singletonTabs[tabId];
    }
    
    // 在所有TabStack中查找
    auto tabStacks = m_primaryArea->getAllTabStacks();
    for (auto stack : tabStacks) {
        auto tabs = stack->tabs();
        for (auto tab : tabs) {
            if (getTabId(tab) == tabId) {
                return tab;
            }
        }
    }
    
    return nullptr;
}

QList<DockTab*> TabManager::findAllTabsOfType(const QString& tabId) const {
    QList<DockTab*> result;
    if (!m_primaryArea) return result;
    
    auto tabStacks = m_primaryArea->getAllTabStacks();
    for (auto stack : tabStacks) {
        auto tabs = stack->tabs();
        for (auto tab : tabs) {
            if (getTabId(tab) == tabId) {
                result.append(tab);
            }
        }
    }
    
    return result;
}

QList<DockTab*> TabManager::getAllActiveTabs() const {
    QList<DockTab*> result;
    if (!m_primaryArea) return result;
    
    auto tabStacks = m_primaryArea->getAllTabStacks();
    for (auto stack : tabStacks) {
        auto tabs = stack->tabs();
        result.append(tabs);
    }
    
    return result;
}

// === 布局管理 ===

void TabManager::saveLayout(const QString& layoutName) {
    QSettings settings;
    settings.beginGroup("TabManager");
    settings.beginGroup("Layouts");
    settings.beginGroup(layoutName);
    
    // 保存当前布局信息
    if (m_primaryArea) {
        // 这里可以实现详细的布局序列化
        // 暂时保存基本信息
        auto allTabs = getAllActiveTabs();
        QStringList tabIds;
        for (auto tab : allTabs) {
            QString tabId = getTabId(tab);
            if (!tabId.isEmpty()) {
                tabIds.append(tabId);
            }
        }
        settings.setValue("ActiveTabs", tabIds);
    }
    
    settings.endGroup();
    settings.endGroup();
    settings.endGroup();
    
    emit layoutSaved(layoutName);
    qDebug() << "Layout saved:" << layoutName;
}

void TabManager::loadLayout(const QString& layoutName) {
    QSettings settings;
    settings.beginGroup("TabManager");
    settings.beginGroup("Layouts");
    settings.beginGroup(layoutName);
    
    // 加载布局信息
    QStringList tabIds = settings.value("ActiveTabs").toStringList();
    
    // 重新创建标签页
    for (const QString& tabId : tabIds) {
        if (isTabTypeRegistered(tabId)) {
            spawnTab(tabId);
        }
    }
    
    settings.endGroup();
    settings.endGroup();
    settings.endGroup();
    
    emit layoutLoaded(layoutName);
    qDebug() << "Layout loaded:" << layoutName;
}

void TabManager::resetToDefaultLayout() {
    // 清理现有标签页
    if (m_primaryArea) {
        auto tabStacks = m_primaryArea->getAllTabStacks();
        for (auto stack : tabStacks) {
            stack->clear();
        }
    }
    
    // 创建默认布局
    createDefaultLayout();
}

// === 私有方法 ===

DockTab* TabManager::createTabFromInfo(const TabSpawnInfo& info, DockingArea* area) {
    // 创建内容widget
    QWidget* content = info.contentFactory();
    if (!content) {
        qWarning() << "Failed to create content for tab:" << info.tabId;
        return nullptr;
    }
    
    // 创建标签页
    DockTab* tab = new DockTab(info.icon, info.displayName);
    tab->setContentWidget(content);
    tab->setProperty("tabId", info.tabId); // 存储tabId用于查找
    
    // 设置标签页属性
    if (!info.isClosable) {
        tab->setTabType(DockTab::TabType::MainTab);
    }
    
    // 添加到第一个可用的TabStack
    auto tabStacks = area->getAllTabStacks();
    if (!tabStacks.isEmpty()) {
        tabStacks.first()->addTab(tab->tabTitle(), content);
    } else {
        // 如果没有TabStack，创建一个
        // 这里需要DockingArea提供创建TabStack的方法
        qWarning() << "No TabStack available for tab:" << info.tabId;
        delete tab;
        delete content;
        return nullptr;
    }
    
    return tab;
}

void TabManager::activateExistingTab(DockTab* tab) {
    if (!tab) return;
    
    // 查找包含此标签页的TabStack并激活
    if (m_primaryArea) {
        QList<DockingTabStack*> tabStacks = m_primaryArea->getAllTabStacks();
        for (DockingTabStack* stack : tabStacks) {
            if (stack->tabs().contains(tab)) {
                stack->setCurrentTab(tab);
                break;
            }
        }
    }
}

QString TabManager::getTabId(DockTab* tab) const {
    if (!tab) return QString();
    return tab->property("tabId").toString();
}

void TabManager::createDefaultLayout() {
    // 创建默认的编辑器标签页
    if (isTabTypeRegistered("Viewport")) {
        spawnTab("Viewport");
    }
    if (isTabTypeRegistered("ContentBrowser")) {
        spawnTab("ContentBrowser");
    }
    if (isTabTypeRegistered("WorldOutliner")) {
        spawnTab("WorldOutliner");
    }
    if (isTabTypeRegistered("DetailsPanel")) {
        spawnTab("DetailsPanel");
    }
}
